package hua.sndandrcv;

import com.ibm.mq.*;

/**
 * 
 * 从应用程序队列上获取消息的接收应用程序
 * 
 * @author HuangHua
 * 
 */
public class PtpReceiver {
	@SuppressWarnings( { "deprecation", "unchecked" })
	public static void main(String args[]) {
		try {
			String hostName = "192.168.17.183";
			String channel = "SYSTEM.ADMIN.SVRCONN";
			String qManager = "QM_CRM_TEST";
			String qName = "QU_FOSS_ORDER_001_IN";
			int port = 1414;
			String userID = "mqm";
			String password = "mqm";

			/* 设置MQEnvironment 属性以便客户机连接 */
			MQEnvironment.hostname = hostName;
			MQEnvironment.channel = channel;
			// MQEnvironment.properties.put(MQC.TRANSPORT_PROPERTY,MQC.TRANSPORT_WEBSPHERE
			// MQ);
			MQEnvironment.properties.put(MQC.TRANSPORT_PROPERTY,
					MQC.TRANSPORT_MQSERIES_CLIENT);
			MQEnvironment.port = port;
			MQEnvironment.userID = userID;
			MQEnvironment.password = password;

			/* 连接到队列管理器 */
			MQQueueManager qMgr = new MQQueueManager(qManager);

			/*
			 * 设置打开选项以便打开用于输出的队列，如果队列管理器停止，我们也 已设置了选项去应对不成功情况
			 */
			int openOptions = MQC.MQOO_INPUT_SHARED
					| MQC.MQOO_FAIL_IF_QUIESCING;

			/* 打开队列 */
			MQQueue queue = qMgr.accessQueue(qName, openOptions, null, null,
					null);

			/* 设置放置消息选项 */
			MQGetMessageOptions gmo = new MQGetMessageOptions();

			/* 在同步点控制下获取消息 */
			gmo.options = gmo.options + MQC.MQGMO_SYNCPOINT;

			/* 如果在队列上没有消息则等待 */
			gmo.options = gmo.options + MQC.MQGMO_WAIT;

			/* 如果队列管理器停顿则失败 */
			gmo.options = gmo.options + MQC.MQGMO_FAIL_IF_QUIESCING;

			/* 设置等待的时间限制 */
			gmo.waitInterval = 3000;

			/* 创建MQMessage 类 */
			MQMessage inMsg = new MQMessage();

			/* 从队列到消息缓冲区获取消息 */
			queue.get(inMsg, gmo); // 一条一条的取数据

			/* 从消息读取用户数据 */
			String msgString = inMsg.readString(inMsg.getMessageLength());
			System.out.println(" The Message from the Queue is : " + msgString);

			/* 提交事务 */
			qMgr.commit();

			/* 关闭队列和队列管理器对象 */
			queue.close();
			qMgr.disconnect();
		} catch (MQException ex) {
			System.out.println("An MQ Error Occurred: Completion Code is :\t"
					+ ex.completionCode + "\n\n The Reason Code is :\t"
					+ ex.reasonCode);
			ex.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
